package common

import (
	"digital/server/model"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	_ "github.com/spf13/viper"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
)

var DB *gorm.DB
var COS *cos.Client

func InitDB() *gorm.DB {
	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	//字符串中的一些敏感信息应该通过其他方式配置，提高安全性
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset)

	db, err := gorm.Open(driverName, args)
	if err != nil {
		panic("failed to connect database,err:" + err.Error())
	}

	//自动创建数据库表
	db.AutoMigrate(&model.Club{})
	db.AutoMigrate(&model.User{})
	db.AutoMigrate(&model.CImage{})

	DB = db
	return db
}

func GetDB() *gorm.DB {
	return DB
}

// 初始化COS客户端
func InitCOS() *cos.Client {
	bucketName := viper.GetString("cos.bucketName")
	appID := viper.GetString("cos.appID")
	region := viper.GetString("cos.region")
	secretID := viper.GetString("cos.secretID")
	secretKey := viper.GetString("cos.secretKey")

	// 构建Bucket URL
	bucketURL := fmt.Sprintf("https://%s-%s.cos.%s.myqcloud.com", bucketName, appID, region)
	u, _ := url.Parse(bucketURL)
	transport := &cos.AuthorizationTransport{
		SecretID:  secretID,
		SecretKey: secretKey,
	}

	cosClient := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{
		Transport: transport,
	})
	COS = cosClient
	return cosClient
}

// 获取COS客户端实例
func GetCOS() *cos.Client {
	return COS
}
